using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using SJVars;
using SJXmlP.XMLClasses;
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using yW5Lib;

namespace yWriter6
{
	public class clsExportToRTF
	{
		private const string RTFPageBreak = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang3081\\uc1 \\pard \\page \\widowctrl \\par }";

		private string DefaultFontName;

		private float DefaultFontSize;

		private bool SaveUnused;

		private clsProject cProject;

		public clsExportToRTF()
		{
			DefaultFontName = clsShared.cSettings.sGet("EditorFontName", "Segoe UI");
			DefaultFontSize = clsShared.cSettings.sGet("EditorFontSize", 10f);
		}

		public void ExportToRTF(clsProject ProjectClass, bool ByChapter, bool SaveSummaries)
		{
			//Discarded unreachable code: IL_024d, IL_0264, IL_026f, IL_027f, IL_031d, IL_031f, IL_0333, IL_0355
			int num = default(int);
			int num3 = default(int);
			try
			{
				ProjectData.ClearProjectError();
				num = 2;
				int num2 = 2;
				cProject = ProjectClass;
				num2 = 3;
				string text = "";
				num2 = 4;
				clsCollection<int> clsCollection = new clsCollection<int>();
				num2 = 5;
				frmPickChapters frmPickChapters = new frmPickChapters(ref cProject);
				num2 = 6;
				frmPickChapters.EnableAllPresets();
				num2 = 7;
				frmPickChapters.ShowDialog();
				num2 = 8;
				if (!frmPickChapters.Cancelled)
				{
					num2 = 10;
					clsCollection = frmPickChapters.PickedIDs;
					num2 = 11;
					SaveUnused = frmPickChapters.WithUnused;
					num2 = 12;
					if (ByChapter)
					{
						num2 = 13;
						DoExport(text, ByChapter, ref cProject, ref clsCollection, AskForOutputFile: false, SaveSummaries);
						num2 = 14;
						clsShared.cFile.RunFile(clsShared.cFile.PathOnly(text));
					}
					else
					{
						num2 = 16;
						if (frmPickChapters.optAllPresets.Checked)
						{
							num2 = 17;
							IEnumerator enumerator = cProject.cExports.GetEnumerator();
							while (enumerator.MoveNext())
							{
								clsExport clsExport = (clsExport)enumerator.Current;
								num2 = 18;
								text = clsExport.Filename;
								num2 = 19;
								if (Operators.CompareString(text, "", TextCompare: false) == 0)
								{
									num2 = 20;
									text = Path.Combine(cProject.ExportFolder(), clsShared.cFile.FileOnly(clsShared.cFile.FileWithoutExt(cProject.FileWithPath)) + ".rtf");
								}
								else
								{
									num2 = 22;
									text = Path.Combine(cProject.ExportFolder(), text + ".rtf");
								}
								num2 = 23;
								clsCollection = cProject.SelectedChapterIDs(clsExport.ChIDsSemiColonSeparated, frmPickChapters.WithUnused);
								num2 = 24;
								DoExport(text, ByChapter: false, ref cProject, ref clsCollection, AskForOutputFile: false, SaveSummaries);
								num2 = 25;
							}
							num2 = 26;
							if (enumerator is IDisposable)
							{
								(enumerator as IDisposable).Dispose();
							}
							num2 = 27;
							clsShared.cFile.RunFile(cProject.ExportFolder());
						}
						else
						{
							num2 = 29;
							text = clsShared.cFileSel.GetOutputFilename("Specify an .rtf file to export to", cProject.ExportFolder(), "Exported Project.rtf", "*.rtf", !clsShared.cSettings.sGet("OverwriteExport", DefaultIfUnknown: false));
							num2 = 30;
							if (Operators.CompareString(text, "", TextCompare: false) != 0)
							{
								num2 = 31;
								DoExport(text, ByChapter, ref cProject, ref clsCollection, AskForOutputFile: false, SaveSummaries);
								num2 = 32;
								clsShared.cFile.RunFile(clsShared.cFile.PathOnly(text));
							}
						}
					}
				}
			}
			catch (Exception obj) when ((num != 0) & (num3 == 0))
			{
				ProjectData.SetProjectError(obj);
				/*Error near IL_0353: Could not find block for branch target IL_031f*/;
			}
			if (num3 != 0)
			{
				ProjectData.ClearProjectError();
			}
		}

		private void DoExport(string Filename, bool ByChapter, ref clsProject cProject, ref clsCollection<int> colIDs, bool AskForOutputFile, bool SaveSummaries)
		{
			RichTextBox fRT = new RichTextBox();
			RichTextBox fRTFTitle = new RichTextBox();
			RichTextBox rtbChapter = new RichTextBox();
			fRT.Text = "";
			fRT.Font = new Font(DefaultFontName, DefaultFontSize, FontStyle.Regular);
			int num = 0;
			IEnumerator enumerator = default(IEnumerator);
			try
			{
				enumerator = colIDs.GetEnumerator();
				while (enumerator.MoveNext())
				{
					int iD = Conversions.ToInteger(enumerator.Current);
					clsChapter clsChapter = cProject.Chapters.ChapterByID(iD);
					bool flag = false;
					if ((!clsChapter.Unused & (clsChapter.Type == ChapterTypes.ChapterNormal)) | SaveUnused)
					{
						num++;
						if (fRT.TextLength > 0)
						{
							fRT.Select(fRT.TextLength - 1, 0);
						}
						int sceneCount = clsChapter.SceneCount;
						for (int i = 1; i <= sceneCount; i++)
						{
							int iD2 = clsChapter.get_SceneIDByIndex(i);
							clsScene clsScene = cProject.get_SceneByID(iD2);
							if ((SaveUnused | !clsScene.Unused) && PassesExportFilters(clsScene, ByChapter))
							{
								if (SaveSummaries)
								{
									if (!flag)
									{
										AddChapterBreak(num, ref fRT, clsChapter, ref fRTFTitle, DefaultFontName);
										flag = true;
									}
									fRTFTitle.Text = clsScene.Title;
									fRTFTitle.SelectAll();
									fRTFTitle.SelectionFont = new Font(DefaultFontName, DefaultFontSize, FontStyle.Bold);
									fRT.SelectedRtf = fRTFTitle.Rtf;
									fRTFTitle.Text = "\r\nDesc: " + clsScene.DescText.TrimEnd('\r') + "\r\n\r\n";
									fRTFTitle.SelectAll();
									fRTFTitle.SelectionFont = new Font(DefaultFontName, DefaultFontSize, FontStyle.Italic);
									fRT.SelectedRtf = fRTFTitle.Rtf;
									if (Operators.CompareString(clsScene.Notes.Trim(), "", TextCompare: false) != 0)
									{
										fRTFTitle.Text = "\r\nNotes: " + clsScene.Notes.TrimEnd('\r') + "\r\n\r\n";
										fRTFTitle.SelectAll();
										fRTFTitle.SelectionFont = new Font(DefaultFontName, DefaultFontSize, FontStyle.Italic);
										fRT.SelectedRtf = fRTFTitle.Rtf;
									}
								}
								string RTFText = modSubs.RTFWithParsedVars(cProject, clsScene, modVariables.eFinalExportType.Rtf);
								modSubs.ReformatRTFPara(ref RTFText);
								rtbChapter.Rtf = RTFText;
								if (rtbChapter.Text.Trim().Length > 0)
								{
									if (!flag)
									{
										AddChapterBreak(num, ref fRT, clsChapter, ref fRTFTitle, DefaultFontName);
										flag = true;
									}
									InsertImages(ref rtbChapter);
									if (rtbChapter.Text.Contains("<") & rtbChapter.Text.Contains(">"))
									{
										rtbChapter.Rtf = rtbChapter.Rtf.Replace("<RTF ", "");
										rtbChapter.Rtf = rtbChapter.Rtf.Replace("/RTF>", "");
										rtbChapter.Rtf = rtbChapter.Rtf.Replace("<rtf ", "");
										rtbChapter.Rtf = rtbChapter.Rtf.Replace("/rtf>", "");
										if (Strings.InStr(rtbChapter.Text, "<RTFBRK>", CompareMethod.Text) == 0)
										{
											string LoadedString = rtbChapter.Rtf;
											clsShared.cHtml.ConvertBR(ref LoadedString);
											rtbChapter.Rtf = LoadedString;
											ClearTex(ref rtbChapter);
											ClearHTM(ref rtbChapter);
											LoadedString = rtbChapter.Rtf;
											clsShared.cHtml.StripHTML(ref LoadedString);
											fRT.SelectedRtf = LoadedString;
										}
										else
										{
											string LoadedString2 = rtbChapter.Rtf;
											clsShared.cHtml.ConvertBR(ref LoadedString2);
											LoadedString2 = Strings.Replace(LoadedString2, "<p class='chapter'>", "");
											LoadedString2 = (rtbChapter.Rtf = Strings.Replace(LoadedString2, "</p>", ""));
											ClearTex(ref rtbChapter);
											ClearHTM(ref rtbChapter);
											LoadedString2 = rtbChapter.Rtf;
											clsShared.cHtml.StripHTML(ref LoadedString2);
											fRT.SelectedRtf = LoadedString2;
										}
									}
									else
									{
										fRT.SelectedRtf = rtbChapter.Rtf;
									}
									if (i < clsChapter.SceneCount)
									{
										clsScene clsScene2 = cProject.get_SceneByChID(clsChapter.ID, i + 1);
										if ((!clsScene2.Unused & PassesExportFilters(clsScene2, ByChapter)) && !clsScene2.AppendToPrevious)
										{
											fRTFTitle.Text = "***\r\n";
											fRTFTitle.SelectAll();
											fRTFTitle.SelectionFont = new Font(DefaultFontName, DefaultFontSize, FontStyle.Bold);
											fRTFTitle.SelectionAlignment = HorizontalAlignment.Center;
											fRT.SelectedRtf = fRTFTitle.Rtf;
										}
									}
								}
							}
						}
					}
					if (ByChapter)
					{
						ReplaceBreaks(ref fRT);
						ClearTex(ref fRT);
						ClearHTM(ref fRT);
						ClearBlankLines(ref fRT);
						if (Operators.CompareString(fRT.Text.Trim(), "", TextCompare: false) != 0)
						{
							Filename = Path.Combine(cProject.ExportFolder(), clsChapter.Title) + ".rtf";
							clsShared.cFile.WriteTextFile(Filename, fRT.Rtf);
						}
						fRT.Clear();
					}
				}
			}
			finally
			{
				if (enumerator is IDisposable)
				{
					(enumerator as IDisposable).Dispose();
				}
			}
			if (!ByChapter)
			{
				ReplaceBreaks(ref fRT);
				ClearTex(ref fRT);
				ClearHTM(ref fRT);
				ClearBlankLines(ref fRT);
				clsShared.cFile.WriteTextFile(Filename, fRT.Rtf);
			}
		}

		private void AddChapterBreak(int ChapterCount, ref RichTextBox fRT, clsChapter Chapter, ref RichTextBox fRTFTitle, string DefaultFontName)
		{
			if (ChapterCount > 1)
			{
				fRT.SelectedRtf = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang3081\\uc1 \\pard \\page \\widowctrl \\par }";
			}
			fRT.SelectedText = "\r\n";
			if (Chapter.Title.StartsWith("@"))
			{
				fRT.SelectedRtf = "";
				return;
			}
			fRTFTitle.Text = Chapter.Title;
			fRTFTitle.SelectAll();
			fRTFTitle.SelectionFont = new Font(DefaultFontName, 16f, FontStyle.Bold);
			fRTFTitle.SelectionAlignment = HorizontalAlignment.Center;
			fRT.Select(fRT.TextLength - 1, 0);
			fRT.SelectedRtf = fRTFTitle.Rtf;
			fRT.SelectedText = "\r\n";
		}

		private void InsertImages(ref RichTextBox rtbChapter)
		{
			try
			{
				if (rtbChapter.Text.Contains("<rtf img "))
				{
					while (true)
					{
						int num = Strings.InStr(rtbChapter.Text, "<rtf img", CompareMethod.Text);
						if (num > 0)
						{
							int num2 = Strings.InStr(num, rtbChapter.Text, " /img>", CompareMethod.Text);
							if (num2 == 0)
							{
								break;
							}
							string text = Strings.Mid(rtbChapter.Text, num, num2 - num + 6);
							string expression = Strings.Replace(text, "\\\\", "\\");
							expression = Strings.Replace(expression, "<rtf img ", "");
							expression = Strings.Replace(expression, " /img>", "");
							if (!clsShared.cFile.FileExists(expression))
							{
								expression = Path.Combine(cProject.ProjectPath(), expression);
							}
							if (!clsShared.cFile.FileExists(expression))
							{
								Interaction.MsgBox(expression + " not found");
							}
							Image image;
							try
							{
								image = Image.FromFile(expression);
							}
							catch (Exception ex)
							{
								ProjectData.SetProjectError(ex);
								Exception ex2 = ex;
								image = null;
								ProjectData.ClearProjectError();
							}
							rtbChapter.Select(num - 1, text.Length);
							if (image == null)
							{
								rtbChapter.SelectedText = "";
							}
							else
							{
								Clipboard.Clear();
								Clipboard.SetImage(image);
								rtbChapter.SelectionAlignment = HorizontalAlignment.Center;
								rtbChapter.Paste();
							}
						}
						if (num == 0)
						{
							return;
						}
					}
					Interaction.MsgBox("RTF IMG tag left open");
				}
			}
			catch (Exception ex3)
			{
				ProjectData.SetProjectError(ex3);
				Exception ex4 = ex3;
				clsShared.cLog.AddAction(ex4, MethodBase.GetCurrentMethod());
				ProjectData.ClearProjectError();
			}
		}

		private void InsertURLS(ref RichTextBox rtbChapter)
		{
			try
			{
				if (rtbChapter.Text.Contains("<rtf url "))
				{
					string text = rtbChapter.Rtf;
					int num;
					do
					{
						num = Strings.InStr(text, "<rtf url", CompareMethod.Text);
						if (num > 0)
						{
							int num2 = Strings.InStr(num, text, " /url>", CompareMethod.Text);
							if (num2 == 0)
							{
								Interaction.MsgBox("RTF URL tag left open");
								return;
							}
							string text2 = Strings.Mid(text, num, num2 - num + 6).Trim();
							string expression = Strings.Replace(text2, "<rtf url ", "");
							expression = Strings.Replace(expression, " /url>", "");
							if (expression.StartsWith("\\"))
							{
								expression = Strings.Mid(expression, Strings.InStr(expression, " ") + 1);
							}
							expression = HyperlinkToRtf(expression);
							text = Strings.Replace(text, text2, expression);
						}
					}
					while (num != 0);
					rtbChapter.Rtf = text;
				}
			}
			catch (Exception ex)
			{
				ProjectData.SetProjectError(ex);
				Exception ex2 = ex;
				clsShared.cLog.AddAction(ex2, MethodBase.GetCurrentMethod());
				ProjectData.ClearProjectError();
			}
		}

		private bool PassesExportFilters(clsScene Scene, bool ByChapter)
		{
			bool result = false;
			if (!Scene.ExportCondSpecific)
			{
				result = true;
			}
			else if (ByChapter & Scene.ExportWhenRTFChapters)
			{
				result = true;
			}
			else if (!ByChapter & Scene.ExportWhenRTF)
			{
				result = true;
			}
			return result;
		}

		private void ReplaceBreaks(ref RichTextBox fRT)
		{
			string text = "<RTFBRK>";
			while (fRT.Text.Contains(text))
			{
				int start = fRT.Find(text);
				fRT.Select(start, Strings.Len(text));
				fRT.SelectedRtf = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang3081\\uc1 \\pard \\page \\widowctrl \\par }";
			}
			text = "[pb]";
			while (fRT.Text.Contains(text))
			{
				int start = fRT.Find(text);
				fRT.Select(start, Strings.Len(text));
				fRT.SelectedRtf = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang3081\\uc1 \\pard \\page \\widowctrl \\par }";
			}
		}

		private void ClearBlankLines(ref RichTextBox fRT)
		{
			string rtf = fRT.Rtf;
			rtf = Strings.Replace(rtf, "\r\n\\par\r\n", "\r\n");
			fRT.Rtf = rtf;
		}

		private void ClearTex(ref RichTextBox fRT)
		{
			string openTag = "<TEX ";
			string closeTag = " /TEX>";
			ClearUnwanted(ref fRT, openTag, closeTag);
		}

		private void ClearHTM(ref RichTextBox fRT)
		{
			string openTag = "<HTM ";
			string closeTag = "/HTM>";
			ClearUnwanted(ref fRT, openTag, closeTag);
		}

		private void ClearUnwanted(ref RichTextBox fRT, string OpenTag, string CloseTag)
		{
			while (fRT.Text.ToUpper().Contains(OpenTag))
			{
				int num = fRT.Find(OpenTag);
				int num2 = fRT.Find(CloseTag);
				if (num2 > num)
				{
					fRT.Select(num, num2 - num + Strings.Len(CloseTag));
					fRT.SelectedText = "";
					continue;
				}
				break;
			}
		}

		private string HyperlinkToRtf(string strCode)
		{
			if (!strCode.Contains("||"))
			{
				return "";
			}
			string[] array = Strings.Split(strCode, "||");
			string expression = array[0].Trim();
			string expression2 = array[1].Trim();
			expression = Strings.Replace(expression, "\\\\", "\\");
			expression2 = Strings.Replace(expression2, "\\", "\\\\");
			return Strings.Replace(Strings.Replace("{\\*\\generator Riched20 10.0.17134}\\viewkind4\\uc1 \\pard\\hyphpar0\\widctlpar {\\kerning1\\f0\\fs24\\lang3081{\\field{\\*\\fldinst{HYPERLINK \"$URL\" }}{\\fldrslt{\\ul\\cf1\\cf2\\ul\\lang255 $Text}}}}", "$URL", expression2), "$Text", expression);
		}
	}
}
